<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2016/9/1
 * Time: 19:13
 * 定时脚本拉取数据，爬出有用的数据记录，第二天再来查看 放在服务器上定时去跑
 */


error_reporting(E_ERROR);
date_default_timezone_set('PRC');
define("URL", "http://www.t-cat.com.tw/Inquire/Trace.aspx?no=");
define('DB_HOST', 'localhost');
define('DB_USER', 'root');
define('DB_PWD', 'jh!@#2016');
define('DB_NAME', 'analysis');
define('DB_PORT', '3306');
define('DB_CHARSET', 'utf8');
define('DB_TYPE', 'mysql');

//从数据库读出原始数据，处理完成之后将状态标记回去
try {
    $dsn = 'mysql:dbname=' . DB_NAME . ';host=' . DB_HOST . ';port=' . DB_PORT;
    $user = DB_USER;
    $password = DB_PWD;
    $dbh = new PDO($dsn, $user, $password);
    $dbh->query("set names utf8");
    $sql = "select * from id_nums where status = 0";
    $result_conn = $dbh->query($sql)->fetchAll();
    foreach ($result_conn as $cont) {
        if (empty($cont['num'])) {
            continue;
        }
        $no_html = http_get(trim($cont['num']));//发送请求


        //因为不是数据接口，所以返回的是个html页面 所以要来抓取页面里面的东西
        $zz_res = format_html($no_html, trim($cont['num']));


        $nzz[0] = $zz_res[0];
        $nzz[1] = $zz_res[1];
        $nzz[2] = $zz_res[2];
        $nzz[3] = $zz_res[3];

        $nos[] = $nzz;
    }


    //分析完成的数据插入log表中
    $result = save_data($nos);
    if ($result) {
        //更新原是表中状态
        foreach ($nos as $n) {
            $log_ret = update_status(trim($n[0]));
            //打一条日志
            if ($log_ret) {
                $status = '成功';
            } else {
                $status = '失败';
            }
            write_log('update', "num->" . $n[0] . "的状态更新" . $status);
        }

        echo "脚本处理完毕";
    }

} catch (Exception $e) {
    echo $e->getMessage();
    exit;
}

function write_log($action, $content)
{
    $logfile = dirname(__FILE__) . '/../logs/heimao_updatestatus_log' . date('Ymd') . '.txt';

    if (!file_exists($logfile)) {
        @touch($logfile);
    }
    error_log(date("[Y-m-d H:i:s]") . " -[" . $action . "] :" . $content . "\n", 3, $logfile);
}


//更新原始表状态
function update_status($num)
{

    $arrayDataValue = ['status' => '-1'];
    $table = 'id_nums';
    $where = 'num=' . $num;
    $strSql = '';
    foreach ($arrayDataValue as $key => $value) {
        $strSql .= ", `$key`='$value'";
    }
    $strSql = substr($strSql, 1);
    $strSql = "UPDATE `$table` SET $strSql WHERE $where";

    $dsn = 'mysql:dbname=' . DB_NAME . ';host=' . DB_HOST . ';port=' . DB_PORT;
    $user = DB_USER;
    $password = DB_PWD;
    $dbh = new PDO($dsn, $user, $password);
    $dbh->query("set names utf8");
    $ret = $dbh->exec($strSql);
    return $ret;
}


function save_data($data)
{
    foreach ($data as $d) {
        $new_data['num'] = $d[0];
        $new_data['status'] = $d[1];
        $new_data['order_time'] = $d[2];
        $new_data['owner_addr'] = $d[3];
        $new_data['createtime'] = date('Y-m-d H:i:s');
        $newDatas[] = $new_data;
    }

    return mulit_insert('bd_data_logs', $newDatas);
}


function mulit_insert($table, $arrData)
{
    $name = $values = '';
    $flag = $flagV = 1;
    $true = is_array(current($arrData));//判断是否一次插入多条数据
    if ($true) {
        //构建插入多条数据的sql语句
        foreach ($arrData as $arr) {
            $values .= $flag ? '(' : ',(';
            foreach ($arr as $key => $value) {
                if ($flagV) {
                    if ($flag) $name .= "$key";
                    $values .= "'$value'";
                    $flagV = 0;
                } else {
                    if ($flag) $name .= ",$key";
                    $values .= ",'$value'";
                }
            }
            $values .= ') ';
            $flag = 0;
            $flagV = 1;
        }
    } else {
        //构建插入单条数据的sql语句
        foreach ($arrData as $key => $value) {
            if ($flagV) {
                $name = "$key";
                $values = "('$value'";
                $flagV = 0;
            } else {
                $name .= ",$key";
                $values .= ",'$value'";
            }
        }
        $values .= ") ";
    }

    $dsn = 'mysql:dbname=' . DB_NAME . ';host=' . DB_HOST . ';port=' . DB_PORT;
    $user = DB_USER;
    $password = DB_PWD;
    $dbh = new PDO($dsn, $user, $password);
    $dbh->query("set names utf8");
    $strSql = "replace into $table ($name) values $values";
    $ret = $dbh->exec($strSql);
    return $ret;
}

function http_get($value)
{
    $url = URL . $value;
    $ch = curl_init();
    $timeout = 60;
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
    $result = curl_exec($ch);
    curl_close($ch);
    return $result;
}


function format_html($html, $id)
{
    $result = '';
    if (empty($html)) {
        return $result;
    }


    $sub_str = "<table>";
    $sub_str_td = "您輸入的貨物追蹤查詢號碼如下";

    if (strpos($html, $sub_str)) {
        //位置开始后面的字符串
        $real_html = substr($html, 0, strpos($html, $sub_str));
        if (!empty($real_html) || strpos($real_html, '<tr>') != false) {
            $t1_html = substr($real_html, strpos($real_html, '<tr>'), (strlen($real_html) - strpos($real_html, '<tr>')));
            $t2_html = substr($t1_html, strpos($t1_html, '</tr>'), (strlen($t1_html) - strpos($t1_html, '</tr>')));
            //正则匹配
            $matchall = array();
            preg_match_all('/\<td.+?\>(.+?)\<\/td\>/', $t2_html, $matchall);

        }


        $string = strip_tags($matchall[0][0]);
        $string = htmlspecialchars($string, ENT_QUOTES, 'UTF-8');
        $nm[0] = trim($string);

        $string1 = strip_tags($matchall[0][1]);
        $string1 = htmlspecialchars($string1, ENT_QUOTES, 'UTF-8');
        $nm[1] = trim($string1);

        $string2 = strip_tags($matchall[0][2]);
        $string2 = htmlspecialchars($string2, ENT_QUOTES, 'UTF-8');
        $nm[2] = trim($string2);

        $string3 = strip_tags($matchall[0][3]);
        $string3 = htmlspecialchars($string3, ENT_QUOTES, 'UTF-8');
        $nm[3] = trim($string3);

        $result = $nm;

    } else if (strpos($html, $sub_str_td)) {
        //正在配送的状态
        $result = [$id, "未上线", "", ""];
    } else {
        //非法的单号
        $result = [$id, "非法的单号", "", ""];
    }

    return $result;
}

